import React, { useState } from 'react';
import { message, Modal, Select, Button, App, Form, Input, DatePicker, Radio } from 'antd';
import { login, getDeptList, getPostList, setUserDeptPost, getUserInfo, getresource, getDepartmentList, getPositionList } from '@/services/ant-design-pro/api';
import { userpageadd } from '@/services/system/user';
import { history, useModel } from '@umijs/max';
import { flushSync } from 'react-dom';
import { setToken } from '@/utils/auth';
import { LockOutlined, UserOutlined, EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons';
import moment from 'moment';
import shouyebeij from '@/components/Imges/aigeicom.gif';
// 类型定义
type DeptOption = {
  value: string;
  label: string;
  institutionId: string;
};

type PostOption = {
  value: string;
  label: string;
  };

  type DepartmentOption = {
    value: string;
    label: string;
    departmentId: string;
  };

  type PositionOption = {
    value: string;
    label: string;
    positionId: string;
  };

const Login: React.FC = () => {
  const [submitting, setSubmitting] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const { initialState, setInitialState } = useModel('@@initialState');
  const [isRegisterMode, setIsRegisterMode] = useState(false);
  const [form] = Form.useForm();

  // 机构角色选择相关状态
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [deptOptions, setDeptOptions] = useState<DeptOption[]>([]);
  const [postOptions, setPostOptions] = useState<PostOption[]>([]);
  const [departmentOptions, setDepartmentOptions] = useState<DepartmentOption[]>([]);
  const [positionOptions, setPositionOptions] = useState<PositionOption[]>([]);
  const [selectedDept, setSelectedDept] = useState<string>();
  const [selectedPost, setSelectedPost] = useState<string>();
  const [selectedDepartment, setSelectedDepartment] = useState<string>();
  const [selectedPosition, setSelectedPosition] = useState<string>();
  const [modalLoading, setModalLoading] = useState(false);

  // 获取机构列表
  const fetchDeptList = async () => {
    try {
      const response = await getDeptList();
      if (response.code === 200 && response.data) {
        const options = response.data.map(item => ({
          value: item?.id,
          label: item?.institutionName,
          institutionId: item?.institutionId,
        }));
        setDeptOptions(options);
      } else {
        message.error(response.msg || '获取机构列表失败');
      }
    } catch (error) {
      console.error('获取机构列表错误:', error);
      message.error('获取机构列表失败');
    }
  };

  // 获取角色列表
  const fetchPostList = async (institutionId: string) => {
    try {
      const response = await getPostList({ institutionId });
      if (response.code === 200 && response.data) {
        const options = response.data.map(item => ({
          value: item.institutionRoleId,
          label: item.institutionRoleName,
        }));
        setPostOptions(options);
      } else {
        message.error(response.msg || '获取角色列表失败');
      }
    } catch (error) {
      console.error('获取角色列表错误:', error);
      message.error('获取角色列表失败');
    }
  };

  // 获取部门列表
  const fetchDepartmentList = async (roleId: string) => {
    if (!selectedDept) return;
    try {
      const response = await getDepartmentList({
        institutionRoleId: roleId,
        institutionId: selectedDept
      });

      if (response.code === 200 && response.data) {
        const options = response.data.map(item => ({
          value: item.departmentId,
          label: item.deptName,
          departmentId: item.departmentId,
        }));
        setDepartmentOptions(options);
      } else {
        message.error(response.msg || '获取部门列表失败');
      }
    } catch (error) {
      console.error('获取部门列表错误:', error);
      message.error('获取部门列表失败');
    }
  };

  // 获取岗位列表
  const fetchPositionList = async (departmentId: string) => {
    if (!selectedDept || !selectedPost) return;
    try {
      const response = await getPositionList({
        institutionRoleId: selectedPost,
        institutionId: selectedDept,
        departmentId: departmentId
      });
      if (response.code === 200 && response.data) {
        const options = response.data.map(item => ({
          value: item.positionId,
          label: item.positionName,
          positionId: item.positionId,
        }));
        setPositionOptions(options);
      } else {
        message.error(response.msg || '获取岗位列表失败');
      }
    } catch (error) {
      console.error('获取岗位列表错误:', error);
      message.error('获取岗位列表失败');
    }
  };

  // 获取资源列表
  const fetchResourceList = async () => {
    try {
      const response = await getresource({
        institutionId: selectedDept,
        positionId:selectedPosition ,
        departmentId: selectedDepartment,
        institutionRoleId: selectedPost
      });
      if (response.code === 200 && response.data) {
        return response.data;
      }
      message.error(response.msg || '获取资源列表失败');
      return [];
    } catch (error) {
      console.error('获取资源列表错误:', error);
      message.error('获取资源列表失败');
      return [];
    }
  };

  // 处理选择变化
  const handleDeptChange = (value: string) => {
    setSelectedDept(value);
    setSelectedPost(undefined);
    fetchPostList(value);
  };

  const handlePostChange = (value: string) => {
    setSelectedPost(value);
    setSelectedDepartment(undefined);
    fetchDepartmentList(value);
  };

  const handleDepartmentChange = (value: string) => {
    setSelectedDepartment(value);
    setSelectedPosition(undefined);
    fetchPositionList(value);
  };

  const handlePositionChange = (value: string) => {
    setSelectedPosition(value);
  };

  // 处理模态框确认
  const { setInstitutionId, setInstitutionRoleId, setDepartmentId, setPositionId } = useModel('auth');

  // 在handleModalOk方法中设置全局状态
  const handleModalOk = async () => {
    if (!selectedDept || !selectedPost || !selectedDepartment || !selectedPosition) {
      message.warning('请选择机构、角色、部门和岗位');
      return;
    }

    setModalLoading(true);
    try {
      // 设置全局状态
      setInstitutionId(selectedDept);
      setInstitutionRoleId(selectedPost);
      setDepartmentId(selectedDepartment);
      setPositionId(selectedPosition);

      const deptPostResponse = await setUserDeptPost({
        institutionId: selectedDept,
        positionId: selectedPost,
        departmentId: selectedDepartment,
        institutionRoleId: selectedPosition,
      });

      if (deptPostResponse.code === 200) {
        localStorage.setItem('user_products', JSON.stringify(deptPostResponse.data));

        const userInfoResponse = await getUserInfo();
        if (userInfoResponse.code === 200) {
          localStorage.setItem('user_info', JSON.stringify(userInfoResponse.data));

          const resourceData = await fetchResourceList();

          await setInitialState((s) => ({
            ...s,
            currentUser: userInfoResponse.data,
            menus: resourceData,
            products: deptPostResponse.data,
          }));

          setIsModalOpen(false);
          history.replace('/welcome');
          message.success('登录成功');
        }
      }
    } catch (error) {
      console.error('设置机构角色错误:', error);
      message.error('设置失败，请重试');
    } finally {
      setModalLoading(false);
    }
  };

  // 处理登录提交
  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    const values = {
      username: formData.get('username'),
      password: formData.get('password'),
    };

    try {
      setSubmitting(true);
      const msg = await login(values as API.LoginParams);

      if (msg?.code === 200 && msg.data) {
        message.success('登录成功！');
        setToken(msg.data.access_token);
        await fetchDeptList();
        setIsModalOpen(true);
        return;
      }

      message.error(msg?.msg || '登录失败，请重试！');
    } catch (error) {
      message.error('登录失败，请重试！');
    } finally {
      setSubmitting(false);
    }
  };

  // 处理注册提交
  const handleRegister = async (values: any) => {
    try {
      setSubmitting(true);
      const params = {
        ...values,
        birthday: values.birthday ? moment(values.birthday).format('YYYY-MM-DD') : undefined,
      };

      const response = await userpageadd(params);
      if (response.code === 200) {
        message.success('注册成功！');
        setIsRegisterMode(false);
        form.resetFields();
      } else {
        message.error(response.msg || '注册失败，请重试！');
      }
    } catch (error) {
      console.error('注册失败:', error);
      message.error('注册失败，请重试！');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <App>
      <div style={{ display: 'flex', minHeight: '100vh', background: '#fff' }}>
        <div style={{
          flex: 1,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          background: '#e6f7ff',
          padding: '0',
          position: 'relative',
          overflow: 'hidden'
        }}>
          <img
            src={shouyebeij}
            alt="平台展示"
            style={{
              width: '95%',
              height: '95%',
              objectFit: 'contain',
              position: 'absolute',
              left: '50%',
              top: '50%',
              transform: 'translate(-50%, -50%)',
            }}
          />
              </div>
        <div style={{
          width: isRegisterMode ? '500px' : '400px',
          padding: '40px',
          display: 'flex',
          flexDirection: 'column',
          transition: 'width 0.3s ease'
        }}>
          <div style={{
            display: 'flex',
            alignItems: 'center',
            marginBottom: '40px'
          }}>
            <img
              src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg"
              alt="Logo"
              style={{ width: '32px', height: '32px', marginRight: '12px' }}
            />
            <div style={{
              fontSize: '20px',
              fontWeight: 500,
              color: '#333'
            }}>企业服务平台</div>
              </div>
          <h1 style={{
            fontSize: '24px',
            fontWeight: 500,
            color: '#333',
            marginBottom: '24px'
          }}>{isRegisterMode ? '账号注册' : '账号登录'}</h1>

          {isRegisterMode ? (
            <Form
              form={form}
              layout="vertical"
              onFinish={handleRegister}
              style={{ width: '100%' }}
            >
              <Form.Item
                name="userName"
                label="用户名"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input placeholder="请输入用户名" />
              </Form.Item>

              <Form.Item
                name="password"
                label="密码"
                rules={[{ required: true, message: '请输入密码' }]}
              >
                <Input.Password
                placeholder="请输入密码"
                  iconRender={(visible) => (visible ? <EyeOutlined /> : <EyeInvisibleOutlined />)}
                />
              </Form.Item>

              <Form.Item
                name="confirmPassword"
                label="确认密码"
                dependencies={['password']}
                rules={[
                  { required: true, message: '请确认密码' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不一致'));
                    },
                  }),
                ]}
              >
                <Input.Password
                  placeholder="请再次输入密码"
                  iconRender={(visible) => (visible ? <EyeOutlined /> : <EyeInvisibleOutlined />)}
                />
              </Form.Item>

              <Form.Item
                name="name"
                label="姓名"
                rules={[{ required: true, message: '请输入姓名' }]}
              >
                <Input placeholder="请输入姓名" />
              </Form.Item>

              <Form.Item
                name="sex"
                label="性别"
              >
                <Radio.Group>
                  <Radio value={0}>男</Radio>
                  <Radio value={1}>女</Radio>
                </Radio.Group>
              </Form.Item>

              <Form.Item
                name="birthday"
                label="生日"
                rules={[{ required: true, message: '请选择生日' }]}
              >
                <DatePicker
                  placeholder="请选择生日"
                  style={{ width: '100%' }}
                />
              </Form.Item>

              <Form.Item
                name="phone"
                label="手机号"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                ]}
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>

              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入正确的邮箱格式' }
                ]}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>

              <Form.Item
                name="address"
                label="地址"
                rules={[{ required: true, message: '请输入地址' }]}
              >
                <Input placeholder="请输入地址" />
              </Form.Item>

              <Form.Item style={{ marginTop: '24px' }}>
              <Button
                type="primary"
                htmlType="submit"
                  loading={submitting}
                  style={{
                    width: '100%',
                    height: '40px',
                    borderRadius: '4px'
                  }}
                >
                  注册
              </Button>
              </Form.Item>
            </Form>
          ) : (
            <form onSubmit={handleSubmit}>
              <div style={{ position: 'relative', marginBottom: '16px' }}>
                <input
                  type="text"
                  name="username"
                  placeholder="账号"
                  required
                  style={{
                    width: '100%',
                    height: '40px',
                    padding: '4px 11px',
                    fontSize: '14px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    transition: 'all 0.3s'
                  }}
                />
              </div>
              <div style={{ position: 'relative', marginBottom: '16px' }}>
                <input
                  type={showPassword ? "text" : "password"}
                  name="password"
                  placeholder="密码"
                  required
                  style={{
                    width: '100%',
                    height: '40px',
                    padding: '4px 11px',
                    fontSize: '14px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    transition: 'all 0.3s'
                  }}
                />
                <span
                  onClick={() => setShowPassword(!showPassword)}
                  style={{
                    position: 'absolute',
                    right: '11px',
                    top: '50%',
                    transform: 'translateY(-50%)',
                    cursor: 'pointer',
                    color: '#bfbfbf'
                  }}
                >
                  {showPassword ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                </span>
              </div>
              <div style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                marginBottom: '24px'
              }}>
                <label style={{
                  display: 'flex',
                  alignItems: 'center',
                  cursor: 'pointer'
                }}>
                  <input
                    type="checkbox"
                    name="remember"
                    style={{ marginRight: '8px' }}
                  />
                  <span style={{ fontSize: '14px', color: '#666' }}>下次自动登录</span>
                </label>
                <a
                  href="#"
                  style={{
                    fontSize: '14px',
                    color: '#1890ff',
                    textDecoration: 'none'
                  }}
                >
                  忘记密码？
                </a>
              </div>
              <button
                type="submit"
                disabled={submitting}
                style={{
                  width: '100%',
                  height: '40px',
                  background: '#1890ff',
                  border: 'none',
                  borderRadius: '4px',
                  color: 'white',
                  fontSize: '14px',
                  fontWeight: 500,
                  cursor: 'pointer',
                  transition: 'all 0.3s'
                }}
              >
                {submitting ? '登录中...' : '登录'}
              </button>
            </form>
          )}

          <div style={{ marginTop: '24px', textAlign: 'center' }}>
            <div style={{ fontSize: '14px', color: '#666' }}>
              {isRegisterMode ? '已有账号？' : '没有账号？'}
              <a
                href="#"
                onClick={(e) => {
                  e.preventDefault();
                  setIsRegisterMode(!isRegisterMode);
                  form.resetFields();
                }}
                style={{
                  color: '#1890ff',
                  textDecoration: 'none',
                  marginLeft: '4px'
                }}
              >
                {isRegisterMode ? '立即登录' : '免费注册'}
              </a>
            </div>
          </div>
        </div>

        {/* 机构角色选择弹窗 */}
        <Modal
          title={null}
          open={isModalOpen}
          onOk={handleModalOk}
          onCancel={() => setIsModalOpen(false)}
          footer={null}
          width={400}
          maskClosable={false}
          closable={false}
          centered
        >
          <div style={{ fontSize: '20px', fontWeight: 'bold', textAlign: 'center', marginBottom: '30px', color: '#1890ff' }}>
            选择您的机构和角色
          </div>

          <div style={{ padding: '0 20px' }}>
            <div style={{ marginBottom: '20px' }}>
              <div style={{ marginBottom: '8px', color: '#666', fontSize: '14px' }}>机构</div>
              <Select
                placeholder="请选择机构"
                options={deptOptions}
                value={selectedDept}
                onChange={handleDeptChange}
                style={{ width: '100%' }}
              />
            </div>

            <div style={{ marginBottom: '20px' }}>
              <div style={{ marginBottom: '8px', color: '#666', fontSize: '14px' }}>角色</div>
              <Select
                placeholder="请选择角色"
                options={postOptions}
                value={selectedPost}
                onChange={handlePostChange}
                disabled={!selectedDept}
                style={{ width: '100%' }}
              />
            </div>

            <div style={{ marginBottom: '20px' }}>
              <div style={{ marginBottom: '8px', color: '#666', fontSize: '14px' }}>部门</div>
              <Select
                placeholder="请选择部门"
                options={departmentOptions}
                value={selectedDepartment}
                onChange={handleDepartmentChange}
                disabled={!selectedPost}
                style={{ width: '100%' }}
              />
            </div>

            <div style={{ marginBottom: '20px' }}>
              <div style={{ marginBottom: '8px', color: '#666', fontSize: '14px' }}>岗位</div>
              <Select
                placeholder="请选择岗位"
                options={positionOptions}
                value={selectedPosition}
                onChange={handlePositionChange}
                disabled={!selectedDepartment}
                style={{ width: '100%' }}
              />
            </div>
          </div>

          <div style={{ display: 'flex', justifyContent: 'center', gap: '16px', marginTop: '24px' }}>
            <Button
              style={{ width: '120px', height: '40px', borderRadius: '20px' }}
              onClick={() => setIsModalOpen(false)}
            >
              取消
            </Button>
            <Button
              type="primary"
              style={{ width: '120px', height: '40px', borderRadius: '20px' }}
              onClick={handleModalOk}
              loading={modalLoading}
            >
              确认
            </Button>
          </div>
        </Modal>
      </div>
    </App>
  );
};

export default Login;
